package com.bartender.order.service.impl;

import java.math.BigDecimal;
import java.util.*;

import com.bartender.common.core.domain.AjaxResult;
import com.bartender.drink.mapper.DrinkMapper;
import com.bartender.ingredient.domain.Ingredient;
import com.bartender.ingredient.mapper.IngredientMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.bartender.order.domain.OrderTable;
import com.bartender.order.mapper.OrderTableMapper;
import com.bartender.order.service.IOrderTableService;
import org.springframework.web.bind.annotation.RequestAttribute;

/**
 * 订单管理Service业务层处理
 * 
 * @author bartender
 * @date 2024-12-19
 */
@Service
public class OrderTableServiceImpl implements IOrderTableService 
{
    @Autowired
    private OrderTableMapper orderTableMapper;

    @Autowired
    private DrinkMapper drinkMapper;

    @Autowired
    private IngredientMapper ingredientMapper;

    /**
     * 查询订单管理
     * 
     * @param orderId 订单管理主键
     * @return 订单管理
     */
    @Override
    public OrderTable selectOrderTableByOrderId(Long orderId)
    {
        return orderTableMapper.selectOrderTableByOrderId(orderId);
    }

    @Override
    public List<OrderTable> selectOrderTableByOpenid(String openid) {
        return orderTableMapper.selectOrderTableByOpenid(openid);
    }

    /**
     * 查询订单管理列表
     * 
     * @param orderTable 订单管理
     * @return 订单管理
     */
    @Override
    public List<OrderTable> selectOrderTableList(OrderTable orderTable)
    {
        return orderTableMapper.selectOrderTableList(orderTable);
    }

    /**
     * 新增订单管理
     * 
     * @param orderTable 订单管理
     * @return 结果
     */
    @Override
    public int insertOrderTable(OrderTable orderTable)
    {
        return orderTableMapper.insertOrderTable(orderTable);
    }

    /**
     * 修改订单管理
     * 
     * @param orderTable 订单管理
     * @return 结果
     */
    @Override
    public int updateOrderTable(OrderTable orderTable)
    {
        return orderTableMapper.updateOrderTable(orderTable);
    }

    /**
     * 批量删除订单管理
     * 
     * @param orderIds 需要删除的订单管理主键
     * @return 结果
     */
    @Override
    public int deleteOrderTableByOrderIds(Long[] orderIds)
    {
        return orderTableMapper.deleteOrderTableByOrderIds(orderIds);
    }

    /**
     * 删除订单管理信息
     * 
     * @param orderId 订单管理主键
     * @return 结果
     */
    @Override
    public int deleteOrderTableByOrderId(Long orderId)
    {
        return orderTableMapper.deleteOrderTableByOrderId(orderId);
    }

    /**
     * 查询订单详情
     * 
     * @param orderId 订单ID
     * @return 订单详情
     */
    @Override
    public Map<String, Object> selectOrderDetailByOrderId(Long orderId) {
        Map<String, Object> map = new HashMap<>();
        // 获取订单基本信息
        OrderTable orderTable = orderTableMapper.selectOrderTableByOrderId(orderId);
        map.put("orderInfo", orderTable);
        // 获取订单酒品详情
        List<Map<String, Object>> drinkList = orderTableMapper.selectOrderDrinkByOrderId(orderId);
        map.put("drinkList", drinkList);
        return map;
    }

    @Override
    public List<Map<String, Object>> selectOrderDetailByOpenid(String openid) {
        try {
            // 获取用户的所有订单
            List<OrderTable> orders = orderTableMapper.selectOrderTableByOpenid(openid);

            // 创建一个结果集来存储订单及其详情
            List<Map<String, Object>> result = new ArrayList<>();

            for (OrderTable order : orders) {
                // 获取每个订单的详情
                Map<String, Object> details = new HashMap<>();

                OrderTable orderTable = orderTableMapper.selectOrderTableByOrderIdToFront(order.getOrderId());
                details.put("orderInfo", orderTable);

                if (orderTable.getDiyId() == null) { // 判断 diyId 是否为 null
                    List<Map<String, Object>> drinkList = orderTableMapper.selectOrderDrinkByOrderId(order.getOrderId());
                    details.put("drinkList", drinkList);
                } else {
                    Long diyId = orderTable.getDiyId();
                    String diyName = orderTableMapper.selectDiyNameByDiyId(diyId);
                    details.put("diyName", diyName);
                    List<Map<String, Object>> diySteps = selectDiyDetailByDiyId(diyId); // 获取 DIY 步骤
                    details.put("diySteps", diySteps);
                }

                result.add(details);
            }

            // 返回成功的结果
            return result;
        } catch (Exception e) {
            // 处理异常并返回错误结果
            e.printStackTrace();
            return null;
        }
    }

    @Override
    @Transactional
    public Map<String, Object> createOrder(String openid, Map<String, Object> orderData, Long deptId) {
        try {
            // 1. 创建订单主表记录
            OrderTable orderTable = new OrderTable();
            orderTable.setOpenid(openid);
            orderTable.setOrderStatus("0");  // 设置初始状态
            orderTable.setPaymentStatus("1"); // 设置初始支付状态
            orderTable.setOrderDate(new Date());   // 设置下单时间
            orderTable.setDiyId(null);
            orderTable.setTotalPrice(null);
            orderTable.setPickupNumber(null);
            orderTable.setRemark(null);
            orderTable.setDeptId(deptId);
            orderTableMapper.insertOrderTable(orderTable);
            
            // 2. 插入订单详情
            Long orderId = orderTable.getOrderId();
            List<Map<String, Object>> drinkList = (List<Map<String, Object>>) orderData.get("drinkList");
            BigDecimal totalPrice = BigDecimal.ZERO;
            
            for (Map<String, Object> drink : drinkList) {
                Map<String, Object> orderDrink = new HashMap<>();
                BigDecimal sellPrice = drinkMapper.selectDrinkByDrinkId(Long.parseLong(drink.get("drinkId").toString())).getSellPrice();
                orderDrink.put("order_id", orderId);
                orderDrink.put("drink_id", drink.get("drinkId"));
                orderDrink.put("number", drink.get("number"));
                orderDrink.put("price", sellPrice);

                // 计算总价
                BigDecimal price = new BigDecimal(sellPrice.toString());
                BigDecimal number = new BigDecimal(drink.get("number").toString());
                totalPrice = totalPrice.add(price.multiply(number));
                
                orderTableMapper.insertOrderDrink(orderDrink);
            }
            
            // 3. 更新订单总价
            orderTable.setTotalPrice(totalPrice);
            orderTableMapper.updateOrderTable(orderTable);
            
            // 4. 返回订单信息
            Map<String, Object> result = new HashMap<>();
            result.put("orderId", orderTable.getOrderId());
            result.put("totalPrice", totalPrice);
            return result;
            
        } catch (Exception e) {
            throw new RuntimeException("创建订单失败", e);
        }
    }

    @Override
    @Transactional
    public Map<String, Object> createDiyOrder(String openid, String diyName, Map<String, Object> orderData, Long deptId) {
        try {
            int stepOrder = 0;
            // 1. 创建 DIY 记录
            Long diyId = createDiyRecord(openid, diyName);

            // 2. 插入 DIY 原料映射
            List<Map<String, Object>> ingredientList = (List<Map<String, Object>>) orderData.get("ingredients");
            BigDecimal totalPrice = BigDecimal.ZERO;

            for (Map<String, Object> ingredient : ingredientList) {
                if (ingredient.get("ingredientId") == null) {
                    stepOrder++;
                    String operation = (String) ingredient.get("operation");
                    insertDiyIngredientMapping(diyId, null, null, null, operation, stepOrder);
                    continue;
                }
                stepOrder++;
                Long ingredientId = ((Integer) ingredient.get("ingredientId")).longValue();
                Integer quantity = (Integer) ingredient.get("quantity");
                String container = (String) ingredient.get("container");
                String operation = (String) ingredient.get("operation");

                // 计算单价
                BigDecimal unitPrice = getIngredientPrice(ingredientId);
                totalPrice = totalPrice.add(unitPrice.multiply(new BigDecimal(quantity)));

                // 插入到中间表
                insertDiyIngredientMapping(diyId, ingredientId, quantity, container, operation, stepOrder);
            }

            // 3. 创建 DIY 订单
            return createOrder(openid, totalPrice, diyId, deptId);
        } catch (Exception e) {
            throw new RuntimeException("创建 DIY 订单失败", e);
        }
    }

    private Long createDiyRecord(String openid, String diyName) {
        Map<String, Object> params = new HashMap<>();
        params.put("openid", openid);
        params.put("diyName", diyName);
        orderTableMapper.insertDiyRecord(params);
        Long diyId = orderTableMapper.selectLastDiyId();
        return diyId;
    }

    private BigDecimal getIngredientPrice(Long ingredientId) {
        // 从 ingredient 表中获取原料单价的逻辑
        // 这里要调用相应的 Mapper 方法查询单价
        // ...
        BigDecimal unitPrice = orderTableMapper.selectIngredientPrice(ingredientId);
        return unitPrice; // 返回单价
    }

    private void insertDiyIngredientMapping(Long diyId, Long ingredientId, Integer quantity, String container, String operation, Integer stepOrder) {
        Map<String, Object> params = new HashMap<>();
        params.put("diyId", diyId);
        params.put("ingredientId", ingredientId);
        params.put("quantity", quantity);
        params.put("container", container);
        params.put("operation", operation);
        params.put("stepOrder", stepOrder);
        orderTableMapper.insertDiyIngredientMapping(params);
    }

    private Map<String, Object> createOrder(String openid, BigDecimal totalPrice, Long diyId, Long deptId) {
        // 创建订单的逻辑
        // 这里需要调用相应的 Mapper 方法插入订单数据
        // ...
        OrderTable orderTable = new OrderTable();
        orderTable.setOpenid(openid);
        orderTable.setOrderStatus("0");
        orderTable.setPaymentStatus("1");
        orderTable.setOrderDate(new Date());
        orderTable.setDiyId(diyId);
        orderTable.setTotalPrice(totalPrice);
        orderTable.setPickupNumber(null);
        orderTable.setRemark(null);
        orderTable.setDeptId(deptId);
        orderTableMapper.insertOrder(orderTable);
        Long orderId = orderTable.getOrderId();
        Map<String, Object> orderResult = new HashMap<>();
        orderResult.put("orderId", orderId);
        orderResult.put("totalPrice", totalPrice);
        orderResult.put("diyId", diyId);
        return orderResult; // 返回订单结果
    }

    @Override
    public List<Map<String, Object>> selectDiyDetailByDiyId(Long diyId) {
        List<Map<String, Object>> diyDetails = orderTableMapper.selectDiyDetailByDiyId(diyId);
        for (Map<String, Object> detail : diyDetails) {
            Long ingredientId = (Long) detail.get("ingredient_id");
            if (ingredientId == null) {
                continue;
            }
            Ingredient ingredient = ingredientMapper.selectIngredientByIngredientId(ingredientId);
            String ingredientName = ingredient.getIngredientName();
            String unit = ingredient.getUnit(); // 获取原料单位
            detail.put("ingredientName", ingredientName);
            detail.put("unit", unit); // 将单位添加到结果中
            detail.remove("ingredient_id");
        }
        return diyDetails;
    }

    @Override
    public int updateEvaluation(String evaluation, Long orderId) {
        OrderTable orderTable = new OrderTable();
        orderTable.setOrderId(orderId);
        orderTable.setEvaluation(evaluation);
        return orderTableMapper.updateEvaluation(orderTable);
    }
}
